<template>
  <view class="edit-page">
	  <view>
	  		<u-picker :show="show" :columns="userClasses" :closeOnClickOverlay="true" @confirm="confirm" @cancel="cancel">{{micro.infoCid}}</u-picker>
			<u-row>
				<u-col span="3"><u-button type="primary" size="small" @click="show = true">选择频道</u-button></u-col>
				<u-col span="3">
					<u--text type="info" :text='micro.infoCname' size=24 color="red"> </u--text></u-col>
				<u-col span="6">
						<u--input
							    placeholder="添加关键词"
							    prefixIcon="bookmark"
							    prefixIconStyle="font-size: 22px;color: #2F85FC"
								maxlength="20"
								v-model="micro.infoKeywords"
							></u--input></u-col>
			</u-row>
	  		
			
	  	</view>
    <!-- 文章编辑区 -->
    <view class="article-editor" v-if="contentType === 'article'">
      <!-- 文章标题 -->
      <input 
        type="text" 
        class="article-title" 
        placeholder="请输入文章标题" 
        v-model="article.infoTitle"
      />
      
      <!-- 富文本编辑器 - 使用Uniapp的editor组件 -->
      <view class="rich-editor">
        <!-- 工具栏 -->
        <view class="editor-toolbar">
          <view class="toolbar-group">
            <view class="tool-btn" 
                  @click="toggleFormat('bold')"
                  :class="{ 'active-shadow': activeFormats.bold }">
              <text class="tool-icon font-bold">B</text>
            </view>
            <view class="tool-btn" 
                  @click="toggleFormat('italic')"
                  :class="{ 'active-shadow': activeFormats.italic }">
              <text class="tool-icon font-italic">I</text>
            </view>
            <view class="tool-btn" 
                  @click="toggleFormat('underline')"
                  :class="{ 'active-shadow': activeFormats.underline }">
              <text class="tool-icon font-underline">U</text>
            </view>
          </view>
          
          <view class="toolbar-group">
            <view class="tool-btn" 
                  @click="toggleHeader(1)"
                  :class="{ 'active-shadow': activeFormats.header === 1 }">
              <text class="tool-icon">H1</text>
            </view>
            <view class="tool-btn" 
                  @click="toggleHeader(2)"
                  :class="{ 'active-shadow': activeFormats.header === 2 }">
              <text class="tool-icon">H2</text>
            </view>
            <view class="tool-btn" 
                  @click="toggleHeader(3)"
                  :class="{ 'active-shadow': activeFormats.header === 3 }">
              <text class="tool-icon">H3</text>
            </view>
          </view>
          
          <view class="toolbar-group">
            <view class="tool-btn" 
                  @click="insertImage" 
                  :class="{ 'active-shadow': activeFormats.image }">
              <u-icon name="photo" size="30" color="#666"></u-icon>
            </view>
           <!-- <view class="tool-btn" 
                  @click="toggleFormat('link')"
                  :class="{ 'active-shadow': activeFormats.link }">
              <u-icon name="share" size="30" color="#666"></u-icon>
            </view> -->
            <view class="tool-btn" 
                  @click="toggleFormat('list', 'bullet')"
                  :class="{ 'active-shadow': activeFormats.list === 'bullet' }">
              <u-icon name="menu" size="30" color="#666"></u-icon>
            </view>
          </view>
        </view>
        
        <!-- editor组件 -->
        <editor
          class="editor-content"
          ref="editor"
          :placeholder="placeholder"
          :show-img-size="true"
          :show-img-toolbar="true"
          :show-img-resize="true"
          @input="onEditorInput"
          @ready="onEditorReady"
          @statuschange="onStatusChange"
        ></editor>
        
        <!-- 图片上传提示 -->
        <view class="editor-tip" v-if="imageUploading">
          <text>图片上传中...</text>
        </view>
      </view>
    </view>
    
    <!-- 微头条编辑区 -->
    <view class="micro-editor" v-if="contentType === 'micro'">
      <textarea 
        class="micro-content" 
        placeholder="分享你的想法..." 
        v-model="micro.infoContent"
        rows="6"
      ></textarea>
      
      <!-- 图片上传区域 -->
      <view class="image-upload-area">
        <view 
          class="upload-btn" 
          @click="chooseMicroImages"
          v-if="micro.images.length < 9"
        >
		<u-icon name="plus"  size="24" color="#999"></u-icon>
          <!-- <icon type="photo" size="24" color="#999"></icon> -->
        </view>
        
        <view class="preview-images">
          <view 
            class="preview-img-item" 
            v-for="(img, index) in micro.images" 
            :key="index"
          >
            <image :src="img" class="preview-img" mode="widthFix"></image>
            <view class="delete-img" @click="deleteMicroImage(index)">
              <icon type="clear" size="18" color="#fff"></icon>
            </view>
          </view>
        </view>
      </view>
      
      <view class="micro-word-count">
        <text>{{ micro.infoContent.length }}/300</text>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="content-type-tabs">
        <view 
          class="tab-item" 
          :class="{ active: contentType === 'micro' }"
          @click="selectType('micro')"
        >
          <text class="tab-text">微头条</text>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: contentType === 'article' }"
          @click="selectType('article')"
        >
          <text class="tab-text">文章</text>
        </view>
      </view>
      
      <view class="publish-btn" @click="handlePublish">
        <text class="publish-text">发布</text>
      </view>
    </view>
  </view>
</template>

<script>
	import { mapState } from 'vuex';
export default {
  data() {
    return {
		closeOnClickOverlay:true,
		show: false,
		userClasses: [['全部', 'UHMWPE纤维', '芳纶纤维','碳纤维']],
		displayCategories: [
		  { id: 0, name: '全部' },
		  { id: 1, name: 'UHMWPE纤维' },
		  { id: 2, name: '芳纶纤维' },
		  { id: 3, name: '碳纤维' }
		],
      // 内容类型：article-文章，micro-微头条，默认微头条
      contentType: 'micro',
      // 编辑器上下文
      editorCtx: null,
      // 占位符
      placeholder: '请输入文章内容...',
      // 是否为编辑状态
      isEditing: false,
      // 图片上传状态
      imageUploading: false,
	  login:false,
      // 激活的格式化状态
      activeFormats: {
        bold: false,
        italic: false,
        underline: false,
        header: 0,
        // link: false,
        list: '',
        image: false,
		infoArea:'',
      },
      // 文章数据
      article: {
        infoId: null,
		infoCid:0,
        infoTitle: '',
        infoContent: '',
        infoViewCount: 0,
        infoCommentCount: 0,
		images: [],
		infoLikeCount: 0,
		infoType: 1,
		infoAuthorId:null,
		infoTime:null,
		infoPic:null,
		infoKeywords:null,
		infoArea:'',
      },
      // 微头条数据
      micro: {
        infoId: '',
		infoCid:0,
        infoContent: '',
        images: [],
        infoViewCount: 0,
        infoLikeCount: 0,
        infoCommentCount: 0,
		infoType: 2,
		infoAuthorId:null,
		infoTime:null,
		infoKeywords:null,
      }
    };
  },
  computed: {
  	...mapState(['userInfo', "appProperties"])
  },
  onShow() {
    // 可以在这里从本地存储或接口加载用户信息
    this.loadUserInfo();
	if(uni.getStorageSync("newsCategorySettings")){
		this.displayCategories = uni.getStorageSync("newsCategorySettings")
	}
	this.userClasses = [this.displayCategories.map(item=>item.name)]
  },
  onLoad(options) {
	  this.getArea()
	  
    // 检查是否是编辑已有内容
    if (options.id && options.type) {
      this.isEditing = true;
      this.contentType = options.type;
      
      if (options.type === 'article') {
        this.loadArticle(options.id);
      } else {
        this.loadMicro(options.id);
      }
      
      // 修改导航栏标题为"编辑"
      uni.setNavigationBarTitle({
        title: '编辑'
      });
    } else {
      // 新内容初始化ID和创建时间
      const timestamp = new Date().getTime();
      const id = 'content_' + timestamp + '_' + Math.floor(Math.random() * 1000);
      
      // this.article.id = id;
      // this.article.infoTime = timestamp;
      // this.micro.id = id;
      // this.micro.infoTime = timestamp;
    }
  },
  
  methods: {
	  
	  			// 回调参数为包含columnIndex、value、values
	  	confirm(e) {
	      this.show = false
		  this.micro.infoCname = e.value[0]
		  this.article.infoCname = e.value[0]
		  const selectClass = uni.getStorageSync("newsCategorySettings").find(item => item.name === this.micro.infoCname)
		  this.micro.infoCid = selectClass.id
		  this.article.infoCid = selectClass.id
	  	},
		cancel() {
			this.show = false;
		  },
	  // 加载用户信息
	  loadUserInfo() {
	    // 实际项目中应该从接口或本地存储获取
	    if (this.userInfo) {
	      this.article.infoAuthorId = this.userInfo.appUserId || '';
		  this.micro.infoAuthorId = this.userInfo.appUserId || '';
		  this.login = true
	  
	    }
	  },
    // 编辑器准备就绪
    onEditorReady() {
      const that = this;
      // 获取编辑器上下文
      uni.createSelectorQuery().select('.editor-content').context(function(res) {
        that.editorCtx = res.context;
        
        // 如果是编辑文章，设置编辑器内容
        if (that.isEditing && that.contentType === 'article' && that.article.infoContent) {
          that.editorCtx.setContents({
            html: that.article.infoContent
          });
        }
      }).exec();
    },
    
    // 编辑器内容变化
    onEditorInput(event) {
      this.article.infoContent = event.detail.html;
    },
    
    // 编辑器状态变化
    onStatusChange(res) {
      // 更新激活的格式化状态 activeFormats.bold
      this.activeFormats = {
        bold: res.detail.bold,
        italic: res.detail.italic,
        underline: res.detail.underline,
        header: res.detail.header,
        // link: res.detail.link,
        list: res.detail.list,
        image: res.detail.image
      };
    },
    
    // 切换格式化状态
    toggleFormat(name, value) {
      if (!this.editorCtx) return;
      
      // 执行格式化命令
      if (value !== undefined) {
        this.editorCtx.format(name, value);
      } else {
        this.editorCtx.format(name);
      }
    },
    
    // 切换标题格式
    toggleHeader(level) {
      if (!this.editorCtx) return;
      
      // 如果当前是该级别标题，则取消
      if (this.activeFormats.header === level) {
        this.editorCtx.format('header', 0);
      } else {
        this.editorCtx.format('header', level);
      }
    },
    
    // 插入图片
    insertImage() {
      if (!this.editorCtx) return;
      
      // 显示上传中状态
      this.imageUploading = true;
      
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          
          // 模拟网络延迟
          setTimeout(() => {
            // 插入图片到编辑器
            this.editorCtx.insertImage({
              src: tempFilePaths[0],
              alt: '文章图片',
              width: '100%',
              success: () => {
                console.log('插入图片成功');
              },
              fail: (err) => {
                console.error('取消插入图片:', err);
                uni.showToast({
                  title: '取消插入图片',
                  icon: 'none',
                  duration: 2000
                });
              },
              complete: () => {
                this.imageUploading = false;
              }
            });
          }, 500);
        },
        fail: (err) => {
          console.error('取消选择图片:', err);
          this.imageUploading = false;
          uni.showToast({
            title: '取消选择图片',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    
    // 插入链接
    insertLink() {
      if (!this.editorCtx) return;
      
      uni.showModal({
        title: '插入链接',
        content: '请输入链接地址',
        inputPlaceholder: 'http://',
        success: (res) => {
          if (res.confirm) {
            const url = res.content;
            if (url) {
              this.editorCtx.format('link', url);
            }
          }
        }
      });
    },
    
    // 其他方法保持不变...
    selectType(type) {
      this.contentType = type;
    },
    
    loadArticle(id) {
      const articles = uni.getStorageSync('creation_articles') || [];
      const article = articles.find(item => item.id === id);
      
      if (article) {
        this.article = { ...article };
        
        if (this.editorCtx) {
          this.editorCtx.setContents({
            html: this.article.infoContent
          });
        }
      } else {
        uni.showToast({
          title: '文章不存在',
          icon: 'none',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          }
        });
      }
    },
    
    loadMicro(id) {
      const micros = uni.getStorageSync('creation_micros') || [];
      const micro = micros.find(item => item.id === id);
      
      if (micro) {
        this.micro = { ...micro };
      } else {
        uni.showToast({
          title: '微头条不存在',
          icon: 'none',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          }
        });
      }
    },
    
    chooseMicroImages() {
      const maxCount = 9 - this.micro.images.length;
      
      uni.chooseImage({
        count: maxCount,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          this.micro.images = [...this.micro.images, ...tempFilePaths];
        }
      });
    },
    
    deleteMicroImage(index) {
      this.micro.images.splice(index, 1);
    },
    
    handlePublish() {
      if (!this.contentType) {
        uni.showToast({
          title: '请选择内容类型',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      if (this.contentType === 'article') {
        this.publishArticle();
      } else {
        this.publishMicro();
      }
    },
    
// 文章发布上传
publishArticle() {
  if (!this.article.infoTitle.trim()) {
    uni.showToast({ title: '请输入文章标题', icon: 'none' });
    return;
  }
  if (!this.article.infoContent.trim()) {
    uni.showToast({ title: '请输入文章内容', icon: 'none' });
    return;
  }
  
  this.article.infoCid = this.micro.infoCid


  // 提取文章中的图片
  const imgReg = /<img[^>]+src="([^">]+)"/g;
  const imgUrls = [];
  let match;
  while ((match = imgReg.exec(this.article.infoContent)) !== null) {
    imgUrls.push(match[1]);
  }

  // 先上传图片
  this.uploadImages(imgUrls).then(uploadedUrls => {
    // 替换文章内容中的图片路径
    let content = this.article.infoContent;
    imgUrls.forEach((oldUrl, index) => {
      content = content.replace(oldUrl, uploadedUrls[index]);
	  this.article.infoContent = content
    });
	this.article.infoPic = uploadedUrls[0]

    // 准备上传数据
    const articleData = {
      ...this.article    };

    // 上传文章数据到后台
	this.$request("api/v1/article/publish", "post",articleData).then(result => {
		// 显示保存成功提示
		if (result.code==200) {
		  this.showPublishSuccess();
		} else {
		  uni.showToast({ title: '发布失败', icon: 'none' });
		}
	})
    // uni.request({
    //   url: 'http://你的Java后台地址/api/article/publish',
    //   method: 'POST',
    //   header: {
    //     'Content-Type': 'application/json'
    //   },
    //   data: articleData,
    //   success: (res) => {
    //     if (res.data.success) {
    //       this.showPublishSuccess();
    //     } else {
    //       uni.showToast({ title: '发布失败', icon: 'none' });
    //     }
    //   },
    //   fail: () => {
    //     uni.showToast({ title: '网络错误', icon: 'none' });
    //   }
    // });
  });
},

// 微头条发布上传
publishMicro() {
  if (!this.micro.infoContent.trim() && this.micro.images.length === 0) {
    uni.showToast({ title: '请输入内容或上传图片', icon: 'none' });
    return;
  }

  // 上传图片
  this.uploadImages(this.micro.images).then(uploadedUrls => {
    const microData = {
      ...this.micro,
      images: uploadedUrls
    };

    // 限制字数
    if (microData.infoContent.length > 300) {
      microData.infoContent = microData.infoContent.substring(0, 300);
    }

    // 上传微头条数据
	this.$request("api/v1/micro/publish", "post",microData).then(result => {
		// 显示保存成功提示
		if (result.code==200) {
		  this.showPublishSuccess();
		} else {
		  uni.showToast({ title: '发布失败', icon: 'none' });
		}
	})
    // uni.request({
    //   url: 'http://你的Java后台地址/api/micro/publish',
    //   method: 'POST',
    //   header: {
    //     'Content-Type': 'application/json'
    //   },
    //   data: microData,
    //   success: (res) => {
    //     if (res.data.success) {
    //       this.showPublishSuccess();
    //     } else {
    //       uni.showToast({ title: '发布失败', icon: 'none' });
    //     }
    //   },
    //   fail: () => {
    //     uni.showToast({ title: '网络错误', icon: 'none' });
    //   }
    // });
  });
},

// 图片上传通用方法
uploadImages(imagePaths) {
  return new Promise((resolve, reject) => {
    if (imagePaths.length === 0) {
      resolve([]);
      return;
    }

    const uploadedUrls = [];
    let completedCount = 0;
	let that = this

    imagePaths.forEach((path, index) => {
      uni.uploadFile({
        url: that.$config.baseUrl + 'api/v1/upload/image',
        filePath: path,
        name: 'file',
		header: {
		      'token': this.$store.getters.getToken,  // 假设 token 存储在 Vuex 中
		    },
        formData: {
          'fileType': 'content',
        },
        success: (uploadRes) => {
          const data = JSON.parse(uploadRes.data);
          if (data.code==200) {
            uploadedUrls[index] = data.msg;
          } else {
            uni.showToast({ title: '图片上传失败', icon: 'none' });
            reject();
          }
        },
        fail: () => {
          uni.showToast({ title: '图片上传失败', icon: 'none' });
          reject();
        },
        complete: () => {
          completedCount++;
          if (completedCount === imagePaths.length) {
            resolve(uploadedUrls);
          }
        }
      });
    });

  });
},
    
    showPublishSuccess() {
      uni.showToast({
        title: this.isEditing ? '修改成功' : '发布成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        }
      });
    },
	getUserClasslist(){
		this.$request("api/v1/userClasslist", "get",this.userInfo).then(result => {
			// 显示保存成功提示
			if (result.code==200) {
			  this.showPublishSuccess();
			}
		})
	},
	getArea(){
		uni.request({
		    url: 'https://myip.ipip.net', // 国内可访问的IP查询服务
		    success: (res) => {
		        const publicIp = res.data.trim(); // 返回的IP可能是纯文本，需trim()处理
		        
		        // 按空格分割成数组
		        const ipArray = publicIp.split(' ');
		        
		        // 检查数组是否有第六个值
		        if (ipArray.length >= 5) {
		            this.article.infoArea = ipArray[4]; // 输出第五个值
					this.micro.infoArea = ipArray[4]; // 输出第五个值
		        } else {
		            this.article.infoArea = 'IP未知'; 
		            this.micro.infoArea = 'IP未知'; 
		        }
		    },
		    fail: (err) => {
		        this.article.infoArea = 'IP未知';
		        this.micro.infoArea = 'IP未知'; 
		    }
		});

	}
  }
};
</script>

<style scoped>
/* 样式部分主要增加了active-shadow类 */
.edit-page {
  background-color: #ffffff;
  min-height: 100vh;
  padding-bottom: 60px;
}

.article-editor {
  padding: 16px;
}

.article-title {
  width: 100%;
  font-size: 20px;
  font-weight: bold;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 16px;
  color: #333;
}

.rich-editor {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
}

.editor-toolbar {
  display: flex;
  flex-wrap: wrap;
  background-color: #f5f5f5;
  padding: 8px 10px;
  border-bottom: 1px solid #eee;
}

.toolbar-group {
  display: flex;
  border-right: 1px solid #ddd;
  padding-right: 10px;
  margin-right: 10px;
}

.toolbar-group:last-child {
  border-right: none;
}

.tool-btn {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  margin: 0 2px;
  transition: all 0.2s ease;
}

/* 激活状态的阴影效果 */
.tool-btn.active-shadow {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  background-color: #e9e9e9;
}

.tool-btn:active {
  background-color: #e0e0e0;
}

.tool-icon {
  font-size: 16px;
  color: #333;
}

/* 文本样式类 */
.font-bold {
  font-weight: bold;
}

.font-italic {
  font-style: italic;
}

.font-underline {
  text-decoration: underline;
}

.editor-content {
  min-height: 300px;
  line-height: 1.8;
  padding: 15px;
}

.editor-tip {
  padding: 8px 15px;
  font-size: 14px;
  color: #666;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
}

.micro-editor {
  padding: 16px;
}

.micro-content {
  width: 100%;
  font-size: 16px;
  line-height: 1.6;
  resize: none;
  color: #333;
}

.image-upload-area {
  margin-top: 20px;
}

.upload-btn {
  width: 80px;
  height: 80px;
  border: 1px dashed #ccc;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
}

.preview-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.preview-img-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-img {
  position: absolute;
  top: -5px;
  right: -5px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.micro-word-count {
  text-align: right;
  font-size: 14px;
  color: #999;
  margin-top: 10px;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  display: flex;
  background-color: #fff;
  border-top: 1px solid #eee;
  z-index: 999;
}

.content-type-tabs {
  flex: 3;
  display: flex;
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tab-item.active {
  color: #007aff;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  width: 50%;
  height: 3px;
  background-color: #007aff;
}

.tab-text {
  font-size: 16px;
}

.publish-btn {
  flex: 1;
  background-color: #007aff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.publish-text {
  font-size: 16px;
  font-weight: bold;
}
</style>
    